import api from './utils/api.js';
import cache from './utils/cache.js';
import http from './utils/http.js';

const Towxml = require('/towxml/main');
const Http = new http;
// app.js
App({
  onLaunch() {
    if (!cache.has('token')) {
      this.getToken(cache.get('openid'));
    }

    // 获取当前网络状态
    wx.onNetworkStatusChange(function (res) {
      var networkType = res.networkType
      var isConnected = res.isConnected
      console.log(networkType, isConnected)
      if (isConnected != true) {
        wx.showToast({
          title: "网络无服务",
          icon: "none"
        })
        return
      }
      wx.showToast({
        title: "当前网络状态为：" + networkType,
        icon: "none"
      })
    })
  },
  wxLogin: function () {
    wx.login({
      success: ({
        code
      }) => {
        // 发起网络请求
        Http.httpReq({
          url: api.login,
          method: 'POST',
          data: {
            code
          }
        }).then(ret => {
          let data = ret.data.data;
          cache.forever('openid', data.openid);
          cache.forever('userInfo', data)
          cache.forever('token', data.token);
        })
      }
    })
  },
  getToken: function (openid) {
    if (!openid) {
      this.wxLogin();
    } else {
      Http.httpReq({
        url: api.refreshToken,
        method: 'POST',
        data: {
          openid: openid
        }
      }).then(ret => {
        let data = ret.data.data;
        cache.set('token', data.token, 3600 * 24 * 7);
      })
    }
  },
  towxml: new Towxml(),
  globalData: {
    userInfo: null
  }
})